package org.hbgl.geoentity.admin.web;

import org.hbgl.geoentity.admin.vo.AddressVo;
import org.hbgl.geoentity.admin.vo.TradeVo;
import org.hbgl.geoentity.core.util.ResponseUtil;
import org.hbgl.geoentity.db.domain.GeAuth;
import org.hbgl.geoentity.db.domain.GeStorage;
import org.hbgl.geoentity.db.vo.ColumnBoxVo;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 代码功能：公共接口
 * 开发日期：2022/5/11
 * 作者：蒋海仑
 * 联系方式：
 * 版本更迭说明：
 * 版权信息：河北广联信息技术有限公司
 */
@RestController
@RequestMapping("/public")
@Validated
public class PublicController extends BaseController {

    @PostMapping("/test")
    public Object test(@RequestBody String body) {
        // String tableName = JacksonUtil.parseString(body, "tableName");
        // if (!ObjectUtils.allNotNull(tableName)) {
        //     return ResponseUtil.badArgument();
        // }

        return ResponseUtil.ok();
    }

    private String stringInsertChar(String s, int[] indexArr, String c) {
        StringBuilder sb = new StringBuilder(s);
        for (int i = indexArr.length - 1; i >= 0; i--) {
            sb.insert(indexArr[i], c);
        }
        return sb.toString();
    }

    @GetMapping("/401")
    public Object page401() {
        return ResponseUtil.unlogin();
    }

    @GetMapping("/index")
    public Object pageIndex() {
        return ResponseUtil.ok();
    }

    @GetMapping("/403")
    public Object page403() {
        return ResponseUtil.unauthz();
    }

    /**
     * 获取验证码
     */
    @GetMapping("/kaptcha")
    public Object kaptcha() {
        String kaptcha = doKaptcha();
        if (kaptcha != null) {
            return ResponseUtil.ok(kaptcha);
        }
        return ResponseUtil.fail();
    }

    /**
     * 获取行政区划树
     */
    @GetMapping("/address")
    public Object address() {
        List<AddressVo> list = AddressVo.build(addressAll);
        for (AddressVo lv1 : list) {
            // 没有二级区域（北京市、天津市、上海市、重庆市）
            // 110000,120000,310000,500000
            if (lv1.getId() == 110000 || lv1.getId() == 120000 || lv1.getId() == 310000 || lv1.getId() == 500000) {
                AddressVo lv2 = new AddressVo();
                lv2.setId(lv1.getId());
                lv2.setPid(lv1.getId());
                lv2.setName(lv1.getName());
                lv2.setChildren(lv1.getChildren());
                lv1.setChildren(Collections.singletonList(lv2));
            }
            // 没有三级区域（东莞市、中山市）
            // 441900,442000
            if (lv1.getId() == 440000) {
                for (AddressVo lv2 : lv1.getChildren()) {
                    if (lv2.getId() == 441900 || lv2.getId() == 442000) {
                        AddressVo lv3 = new AddressVo();
                        lv3.setId(lv2.getId());
                        lv3.setPid(lv2.getId());
                        lv3.setName(lv2.getName());
                        lv2.setChildren(Collections.singletonList(lv3));
                    }
                }
            }
            // 没有二级和三级区域（台湾省、香港特别行政区、澳门特别行政区）
            // 710000,810000,820000
            if (lv1.getId() == 710000 || lv1.getId() == 810000 || lv1.getId() == 820000) {
                AddressVo lv3 = new AddressVo();
                lv3.setId(lv1.getId());
                lv3.setPid(lv1.getId());
                lv3.setName(lv1.getName());
                AddressVo lv2 = new AddressVo();
                lv2.setId(lv1.getId());
                lv2.setPid(lv1.getId());
                lv2.setName(lv1.getName());
                lv2.setChildren(Collections.singletonList(lv3));
                lv1.setChildren(Collections.singletonList(lv2));
            }
        }
        return ResponseUtil.ok(list);
    }

    /**
     * 获取行政区划树
     */
    @GetMapping("/addressNode")
    public Object addressNode() {
        List<AddressVo> list = AddressVo.build(addressAll);
        for (AddressVo lv1 : list) {
            // 没有二级区域（北京市、天津市、上海市、重庆市）
            // 110000,120000,310000,500000
            if (lv1.getId() == 110000 || lv1.getId() == 120000 || lv1.getId() == 310000 || lv1.getId() == 500000) {
                AddressVo lv2 = new AddressVo();
                lv2.setId(lv1.getId());
                lv2.setPid(lv1.getId());
                lv2.setName(lv1.getName());
                lv2.setChildren(lv1.getChildren());
                lv1.setChildren(Collections.singletonList(lv2));
            }
            // 没有三级区域（东莞市、中山市）
            // 441900,442000
            if (lv1.getId() == 440000) {
                for (AddressVo lv2 : lv1.getChildren()) {
                    if (lv2.getId() == 441900 || lv2.getId() == 442000) {
                        AddressVo lv3 = new AddressVo();
                        lv3.setId(lv2.getId());
                        lv3.setPid(lv2.getId());
                        lv3.setName(lv2.getName());
                        lv2.setChildren(Collections.singletonList(lv3));
                    }
                }
            }
            // 没有二级和三级区域（台湾省、香港特别行政区、澳门特别行政区）
            // 710000,810000,820000
            if (lv1.getId() == 710000 || lv1.getId() == 810000 || lv1.getId() == 820000) {
                AddressVo lv3 = new AddressVo();
                lv3.setId(lv1.getId());
                lv3.setPid(lv1.getId());
                lv3.setName(lv1.getName());
                AddressVo lv2 = new AddressVo();
                lv2.setId(lv1.getId());
                lv2.setPid(lv1.getId());
                lv2.setName(lv1.getName());
                lv2.setChildren(Collections.singletonList(lv3));
                lv1.setChildren(Collections.singletonList(lv2));
            }
        }
        return ResponseUtil.ok(list);
    }

    /**
     * 获取栏目列表
     */
    @GetMapping("/columnBox")
    public Object columnBox() {
        List<ColumnBoxVo> columnVos = columnService.columnBox();
        List<ColumnBoxVo> build = ColumnBoxVo.build(columnVos);
        return ResponseUtil.ok(build);
    }

    /**
     * 通过末级栏目id栏目层级
     */
    @GetMapping("/levelColumn")
    public Object levelColumn(@NotNull Integer columnId) {
        List<ColumnBoxVo> columnBoxVos = columnService.columnBox();
        List<ColumnBoxVo> build = ColumnBoxVo.buildDRev(columnId, columnBoxVos);
        return ResponseUtil.ok(build);
    }

    /**
     * 修改栏目层级栏目树
     */
    @GetMapping("/columnBoxUp")
    public Object columnBoxUp(@NotNull Integer columnId) {
        List<ColumnBoxVo> columnBoxVos = columnService.columnBox();
        List<ColumnBoxVo> build = ColumnBoxVo.buildUp(columnId, columnBoxVos);
        return ResponseUtil.ok(build);
    }

    /**
     * 获取单位性质列表
     */
    @GetMapping("/unitType")
    public Object unitType() {
        return ResponseUtil.ok(unitTypeAll);
    }

    /**
     * 获取行业树
     */
    @GetMapping("/trade")
    public Object trade() {
        return ResponseUtil.ok(TradeVo.build(tradeAll));
    }

    /**
     * 上传文件
     *
     * @param file 文件
     */
    @PostMapping("/storage/create")
    public Object create(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        GeStorage geStorage = storageService.store(file.getInputStream(), file.getSize(),
                file.getContentType(), originalFilename);
        return ResponseUtil.ok(geStorage);
    }

    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     */
    @GetMapping("/storage/fetch/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        GeStorage geStorage = geStorageService.findByKey(key);
        if (geStorage == null) {
            return ResponseEntity.notFound().build();
        }
        String type = geStorage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=%s", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity.ok().headers(headers).contentType(mediaType).body(file);
    }

    @PostMapping("/addAssess")
    public Object assessState(@RequestBody GeAuth geAuth) {
        if(geAuth != null) {
            nodeService.addAssess(geAuth);
        }
        return ResponseUtil.ok();
    }

    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + new Random().nextInt(1000);
        System.out.println(newFileName);
    }

}
